<template>
    <div v-if="modelValue == STATUS.SPUFORM">
        <!-- :model="form" -->
        <el-form :label-width="100">
            <el-form-item label="SPU名称">
                <el-input type="text" v-model="spuForm.spuName" placeholder="SPU名称"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select v-model="spuForm.tmId" placeholder="请选择" @change="">
                    <el-option v-for="trademark in trademarkList" :key="trademark.id" :label="trademark.tmName"
                        :value="trademark.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" :rows="3" v-model="spuForm.description" placeholder="SPU描述">
                </el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload v-model:file-list="spuImageList" :on-success="handleAvatarSuccess"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :action="action"
                    list-type="picture-card">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" width="70" height="600" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select 
                    v-model="saleInfo" 
                    :placeholder="`还有${ newSaleAttrList.length }个未选择`" 
                    class="mr-10"
                    @change="getSaleAttr"
                >
                    <el-option 
                        v-for="saleAttr in newSaleAttrList" 
                        :key="saleAttr.id" 
                        :label="saleAttr.name"
                        :value="`${saleAttr.id}:${saleAttr.name}`"
                    >
                    </el-option>
                </el-select>
                <el-button type="primary" @click="addSaleAttr">添加销售属性</el-button>
            </el-form-item>
            <el-form-item>
                <el-table :data="spuSaleAttrList" border>
                    <el-table-column type="index" label="序号" width="80" />
                    <el-table-column label="属性名" prop="saleAttrName" width="200"></el-table-column>
                    <el-table-column label="属性值名称列表">
                        <template #default="{ row, $index }">
                            <el-tag v-for="(saleAttrValue,idx) in row.spuSaleAttrValueList"
                                :key="saleAttrValue.baseSaleAttrId" class="mx-1 mr-5" closable
                                :disable-transitions="false" @close="handleClose(row, idx)">
                                {{ saleAttrValue.saleAttrValueName }}
                            </el-tag>
                            <el-input v-if="row.inputVisible" ref="InputRef" v-model="saleAttrValueName"
                                style="width: 100px;" class="ml-1 w-20" size="small"
                                @keyup.enter="handleInputConfirm(row)" @blur="handleInputConfirm(row)" />
                            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
                                新增
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template #default="{ row, $index }">
                            <el-button type="danger" :icon="Delete" size="small" @click="removeSaleAttr($index)">
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSave">保存</el-button>
                <el-button @click="onCancelSave">取消</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, computed, watch } from 'vue'
import trademarkApi, { type trademarkModel } from '@/api/trademark'
import spuApi, { type baseSaleAttrModel, type spuImageModel, type spuModel, type saleAttrModel, type saleAttrValueModel } from '@/api/spu'
import { ElMessage, ElInput, type UploadProps } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue';
import { STATUS } from '../../index.vue'
import useCategoryStore from '@/stores/category'
import Pubsub from 'pubsub-js'
import { cloneDeep } from 'lodash';
defineProps<{
    modelValue: number
}>()
const emit = defineEmits<{
    (event: 'update:modelValue', status: number): void
}>()
const trademarkList = ref<trademarkModel[]>([])
const action = `${import.meta.env.VITE_API_URL}/admin/product/upload`
const saleAttrList = ref<baseSaleAttrModel[]>([])
const spuImageList = ref<spuImageModel[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const categoryStore = useCategoryStore();
// 用来收集的选择的销售属性
const saleInfo = ref('')
// table中要展示的销售属性
const spuSaleAttrList = ref<saleAttrModel[]>([])
// 初始化spuForm
const initSpuForm = (): spuModel => {
    return {
        spuName: '',
        description: '',
        category3Id: categoryStore.category3Id as number,
        tmId: undefined,
        spuSaleAttrList: [],
        spuImageList: []
    }
}
const spuForm = ref<spuModel>(initSpuForm())
// 获取品牌列表
const getTrademarkList = async () => {
    try {
        let result = await trademarkApi.getTrademarkList();
        trademarkList.value = result;
    } catch (error) {
        ElMessage.error('获取品牌列表失败')
    }
}
// 获取销售属性列表
const getBaseSaleAttrList = async () => {
    try {
        let result = await spuApi.baseSaleAttrList();
        saleAttrList.value = result
    } catch (error) {
        ElMessage.error('获取销售属性列表失败')
    }
}
// 上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    let result = uploadFiles.map(item => {
        if (item.response) {
            return {
                imgName: item.name,
                imgUrl: (item.response as any).data,
                name: item.name,
                url: (item.response as any).data,
                response: item.response
            }
        } else {
            return {
                imgName: item.name,
                imgUrl: item.url as string,
                name: item.name,
                url: item.url
            }
        }
    })
    spuImageList.value = result;
}
// 删除回调
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    ElMessage.success('删除成功!')
}
// 预览图回调
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
// 计算一个相同的基本销售属性
const newSaleAttrList = computed(() => {
    return saleAttrList.value.filter(item => {
        return !spuSaleAttrList.value.map(i => i.baseSaleAttrId).includes(item.id)
    })
})
// 获取到选择的销售属性
const saleAttr = ref('')
const getSaleAttr = (val: string) => {
    saleAttr.value = val;
}
// 添加销售属性到table中
const addSaleAttr = () => {
    if (!saleInfo.value) return
    spuSaleAttrList.value.push({
        baseSaleAttrId: Number(saleAttr.value.split(':')[0]),
        saleAttrName: saleAttr.value.split(':')[1],
        spuSaleAttrValueList: [],
        inputVisible: false
    })
    saleInfo.value = ''
}
// 销售属性值相关
const saleAttrValueName = ref('')
const InputRef = ref<InstanceType<typeof ElInput>>()
// 删除属性值
const handleClose = (row: saleAttrModel, idx: number) => {
    row.spuSaleAttrValueList.splice(idx, 1)
}
// 显示input框
const showInput = (row: saleAttrModel) => {
    row.inputVisible = true
    nextTick(() => {
        InputRef.value?.focus();
    })
}
// input聚焦和失焦时
const handleInputConfirm = (row: saleAttrModel) => {
    if (!saleAttrValueName.value) return
    // 去重
    const isRepeat = row.spuSaleAttrValueList.map(item => item.saleAttrValueName).includes(saleAttrValueName.value)
    if (isRepeat) {
        row.inputVisible = false
        saleAttrValueName.value = ''
        ElMessage.warning('输入的值重复,请重新输入')
        return
    }
    row.spuSaleAttrValueList.push({
        baseSaleAttrId: Number(saleAttr.value.split(':')[0]),
        saleAttrValueName: saleAttrValueName.value,
    })
    row.inputVisible = false
    saleAttrValueName.value = ''
}
// 删除单条销售属性
const removeSaleAttr = (index: number) => {
    spuSaleAttrList.value.splice(index, 1)
}
// 监听category3Id的变化
watch(() => categoryStore.category3Id, (nval, oval) => {
    spuForm.value.category3Id = nval as number
})
// 保存
const onSave = async () => {
    spuForm.value.spuImageList = spuImageList.value.map(item => {
        return {
            imgName: item.imgName,
            imgUrl: item.imgUrl
        }
    });
    spuForm.value.spuSaleAttrList = spuSaleAttrList.value.map(item => {
        return {
            baseSaleAttrId: item.baseSaleAttrId,
            saleAttrName: item.saleAttrName,
            spuSaleAttrValueList: item.spuSaleAttrValueList
        }
    })
    try {
        if (spuForm.value.id) {
            await spuApi.updateSpuInfo(spuForm.value);
        } else {
            await spuApi.saveSpuInfo(spuForm.value);
        }
        spuForm.value = initSpuForm();
        spuImageList.value = [],
            spuSaleAttrList.value = []
        emit('update:modelValue', STATUS.SPULIST)
        Pubsub.publish('update')
        ElMessage.success('保存成功')
    } catch (error) {
        ElMessage.error('保存失败,请重试')
    }
}
// 取消
const onCancelSave = () => {
    spuForm.value = initSpuForm();
    spuImageList.value = [];
    spuSaleAttrList.value = [];
    emit('update:modelValue', STATUS.SPULIST)
}
// 获取图片列表
const getSpuImageList = async () => {
    try {
        let result = await spuApi.spuImageList(spuForm.value?.id!)
        spuImageList.value = result.map(item => {
            return {
                ...item,
                name: item.imgName,
                url: item.imgUrl
            }
        })
    } catch (error) {
        ElMessage.error('获取图片列表失败')
    }
}
// 获取销售属性
const getSpuSaleAttrList = async () => {
    try {
        let result = await spuApi.spuSaleAttrList(spuForm.value?.id!)
        spuSaleAttrList.value = result
    } catch (error) {
        ElMessage.error('获取销售属性列表失败')
    }
}
// 获取当前spu信息
const getSpuInfo = (type: string, val: spuModel) => {
    spuForm.value = val;
    getSpuSaleAttrList();
    getSpuImageList();
}
Pubsub.subscribe('getSpuInfo', getSpuInfo)
onMounted(() => {
    getTrademarkList();
    getBaseSaleAttrList();
    spuForm.value = initSpuForm();
})
</script>

<style scoped>

</style>